#!/bin/bash
readonly messageSize="${1:-200}"
readonly batchSize="${2:-200}"
readonly topicCount="${3:-1}"
readonly memQueueSize="${MEM_QUEUE_SIZE:-1000000}"
set -e
set -u

echo "# using --mem-queue-size=$memQueueSize --size=$messageSize --batch-size=$batchSize --topic-count=${topicCount}"

if [ ! -x ./nsqd ]
then
  echo "Please copy executable nsqd here"
  exit
fi
if [ ! -x ./nsqlookupd ]
then
  echo "Please copy executable nsqlookupd here"
  exit
fi

echo "# building bench"
pushd bench_hl >/dev/null
go build -o bench_reader ./bench_reader
go build -o bench_writer ./bench_writer
popd >/dev/null

echo "# running nsqlookupd and nsqd"
rm -f *.dat
./nsqlookupd --broadcast-address=127.0.0.1 >/dev/null 2>&1 &
nsqlookupd_pid=$!
./nsqd --mem-queue-size=$memQueueSize --lookupd-tcp-address=127.0.0.1:4160 --broadcast-address=127.0.0.1 >/dev/null 2>&1 &
nsqd_pid=$!

cleanup() {
    kill -9 $nsqd_pid
    kill -9 $nsqlookupd_pid
    rm -f *.dat
    rm -f *.tmp
}
trap cleanup INT TERM EXIT

sleep 0.3
echo "# creating topic/channel"
for i in $(seq 1 ${topicCount})
do
    curl --silent "http://127.0.0.1:4151/create_topic?topic=sub_bench_${i}" >/dev/null 2>&1
    curl --silent "http://127.0.0.1:4151/create_channel?topic=sub_bench_${i}&channel=ch" >/dev/null 2>&1
done

echo "PUB: "
bench_hl/bench_writer/bench_writer --runfor=10s --size=$messageSize --topic-count=${topicCount} --batch-size=$batchSize 2>&1

echo "SUB: "
bench_hl/bench_reader/bench_reader --runfor=5s --size=$messageSize --topic-count=${topicCount} --channel=ch --cpu-profile=cpu.prof 2>&1
